// pages/enterprise/company-profile/company-profile.ts
import {getEnterpriseDetail} from '../../../api/enterprise';
import { goToPage, PAGES } from '../../../config/pages';
import { isPaidMember, maskContactName, maskPhone, maskAddress } from '../../../utils/userManager.js';

interface ContactPerson {
  name: string;
  title: string;
  phone: string;
}

interface Product {
  name: string;
  model: string;
  price: string;
  category: string;
  specs: string;
  publishDate: string;
}

interface CompanyData {
  name: string;
  logo: string;
  logoFiles: any[];
  attributes: string[];
  categories: string[];
  contactPerson: ContactPerson;
  products: Product[];
  intro: string;
  address: string;
  publishTime: string;
  photos: any[];
  qualifications: any[];
}

interface RawEnterpriseData {
  license_file?: any;
  cert_file?: any;
}

Page({
  data: {
    // 企业基本信息
    companyData: {
      name: '',
      logo: '',
      logoFiles: [],
      attributes: [],
      categories: [],
      contactPerson: {
        name: '',
        title: '业务对接人',
        phone: ''
      },
      products: [],
      intro: '',
      address: '',
      publishTime: '',
      photos: [],
      qualifications: []
    } as CompanyData,
    
    // 页面状态
    searchKeyword: '',
    filteredProducts: [] as Product[],
    
    // 企业ID（从页面参数获取）
    enterpriseId: '',
    
    // 原始企业数据（用于文件预览等功能）
    rawEnterpriseData: {} as RawEnterpriseData,
    
    // 真实的联系人信息（用于拨打电话等操作）
    realContactName: '',
    realContactPhone: ''
  },

  onLoad(options: any) {
    console.log('企业详情页面加载参数:', options);
    
    // 获取企业ID
    const enterpriseId = options.id || options.enterpriseId;
    
    if (!enterpriseId) {
      wx.showToast({
        title: '企业ID不能为空',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
    
    this.setData({
      enterpriseId
    });
    
    // 加载企业数据
    this.loadEnterpriseData(enterpriseId);
  },

  onShow() {
    // 页面显示时刷新数据
    if (this.data.enterpriseId) {
      this.loadEnterpriseData(this.data.enterpriseId);
    }
  },

  // 加载企业数据
  async loadEnterpriseData(enterpriseId: string) {
    try {
      wx.showLoading({
        title: '加载中...'
      });
      
      console.log('加载企业数据:', enterpriseId);
      
      // 调用API获取企业详情数据
      const response = await getEnterpriseDetail(parseInt(enterpriseId));
      
      if (response && response.data) {
        const enterpriseData = response.data;
        
        // 检查当前用户是否为付费会员
        const paid = isPaidMember();
        
        // 转换API数据为页面所需格式
        const logoFiles = enterpriseData.logo_files || [];
        
        // 根据会员状态决定是否脱敏
        let displayContactName = enterpriseData.contact_name || '';
        let displayPhone = enterpriseData.contact_phone || '';
        let displayAddress = enterpriseData.address || '';
        
        if (!paid) {
          // 非付费会员，显示脱敏信息
          displayContactName = maskContactName(displayContactName);
          displayPhone = maskPhone(displayPhone);
          
          // 处理地址脱敏
          // 优先使用省市区信息进行脱敏，否则直接显示 ***
          if (enterpriseData.province || enterpriseData.city || enterpriseData.district) {
            displayAddress = maskAddress(enterpriseData.province, enterpriseData.city, enterpriseData.district);
          } else if (displayAddress && displayAddress.length > 3) {
            // 如果有完整地址但没有省市区字段，隐藏大部分内容
            displayAddress = displayAddress.slice(0, 2) + ' · ***';
          } else {
            displayAddress = '***';
          }
        }
        
        const companyData: CompanyData = {
          name: enterpriseData.name || '',
          logo: logoFiles.length > 0 ? logoFiles[0].url : '',
          logoFiles: logoFiles,
          attributes: [
            enterpriseData.staff_size || '',
            enterpriseData.funding_stage || '',
            enterpriseData.industry || ''
          ].filter(Boolean),
          categories: enterpriseData.categories || [],
          contactPerson: {
            name: displayContactName,
            title: '业务对接人',
            phone: displayPhone
          },
          products: [], // 产品数据需要单独接口获取
          intro: enterpriseData.description || '',
          address: displayAddress,
          publishTime: enterpriseData.add_time || '',
          photos: [],
          qualifications: []
        };
        
        this.setData({
          companyData: companyData,
          filteredProducts: companyData.products,
          rawEnterpriseData: {
            license_file: enterpriseData.license_file,
            cert_file: enterpriseData.cert_file
          },
          // 保存真实的联系人信息，用于拨打电话等操作
          realContactName: enterpriseData.contact_name || '',
          realContactPhone: enterpriseData.contact_phone || ''
        });
        
        console.log('企业数据加载成功:', companyData);
      } else {
        throw new Error('获取企业数据失败');
      }
    } catch (error: any) {
      console.error('加载企业数据失败:', error);
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      });
      
      // 加载失败时使用默认数据
      this.setData({
        filteredProducts: this.data.companyData.products
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 拨打电话
  makePhoneCall() {
    // 检查是否为付费会员
    const paid = isPaidMember();
    
    // 使用真实的电话号码
    const phone = this.data.realContactPhone;
    if (!phone) {
      wx.showToast({
        title: '暂无联系电话',
        icon: 'none'
      });
      return;
    }
    
    // 非付费会员提示需要开通会员
    if (!paid) {
      wx.showModal({
        title: '需要付费会员',
        content: '查看完整联系方式需要购买付费会员，是否立即开通？',
        confirmText: '立即开通',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 跳转到会员开通页面
            goToPage(PAGES.MEMBERSHIP_REGISTER);
          }
        }
      });
      return;
    }
    
    wx.makePhoneCall({
      phoneNumber: phone,
      success: () => {
        console.log('拨打电话成功');
      },
      fail: (error) => {
        console.error('拨打电话失败:', error);
        wx.showToast({
          title: '拨打电话失败',
          icon: 'none'
        });
      }
    });
  },

  // 查看照片
  viewPhoto(e: any) {
    const index = e.currentTarget.dataset.index;
    const photos = this.data.companyData.logoFiles;
    
    if (!photos || photos.length === 0) {
      wx.showToast({
        title: '暂无照片',
        icon: 'none'
      });
      return;
    }
    
    const urls = photos.map(photo => photo.url);
    
    wx.previewImage({
      current: urls[index],
      urls: urls
    });
  },

  // 查看文件
  viewFile(e: any) {
    const index = e.currentTarget.dataset.index;
    const files = this.data.companyData.qualifications;
    
    if (!files || files.length === 0) {
      wx.showToast({
        title: '暂无文件',
        icon: 'none'
      });
      return;
    }
    
    const file = files[index];
    if (file && file.url) {
      wx.downloadFile({
        url: file.url,
        success: (res) => {
          wx.openDocument({
            filePath: res.tempFilePath,
            success: () => {
              console.log('打开文档成功');
            },
            fail: (error) => {
              console.error('打开文档失败:', error);
              wx.showToast({
                title: '无法打开此文件',
                icon: 'none'
              });
            }
          });
        },
        fail: (error) => {
          console.error('下载文件失败:', error);
          wx.showToast({
            title: '下载文件失败',
            icon: 'none'
          });
        }
      });
    }
  },

  // 显示产品列表 - 跳转到产品页面
  showProducts() {
    const enterpriseId = this.data.enterpriseId;
    const enterpriseName = this.data.companyData.name;
    
    if (!enterpriseId) {
      wx.showToast({
        title: '企业ID不能为空',
        icon: 'none'
      });
      return;
    }
    
    // 跳转到企业产品页面
    goToPage(PAGES.ENTERPRISE_PRODUCT, {
      enterpriseId: enterpriseId,
      enterpriseName: enterpriseName
    });
  }
});